
const {ccclass, property} = cc._decorator;

@ccclass
export default class Person extends cc.Component {
    // 人物速度
    @property(cc.Integer)
    speed:number = 0;
    // 人物方向
    sp:cc.Vec2 = cc.v2(0, 0);

    lv:cc.Vec2 = cc.v2(0, 0);

    private Input:{} = { };

    @property
    jumpHeight:number =  0;
    // 主角跳跃持续时间
    @property
    jumpDuration:number = 0;
    // 是否正在跳跃
    isJumping:boolean = false;

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        
        // 初始化键盘输入监听
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this); 
    }

    onKeyDown(event: cc.Event.EventKeyboard) {
        this.Input[event.keyCode] = 1;
    }
    onKeyUp(event: cc.Event.EventKeyboard) {
        this.Input[event.keyCode] = 0;
    }

    moveState() {
        
        let anim:string;
        let scaleX = Math.abs(this.node.scaleX);
        if (this.Input[cc.macro.KEY.a] || this.Input[cc.macro.KEY.left]) {
            this.sp.x = -1;
            this.node.scaleX = scaleX;
        } else if (this.Input[cc.macro.KEY.d] || this.Input[cc.macro.KEY.right]) {
            this.sp.x = 1;
            this.node.scaleX = -scaleX;
        } else {
            this.sp.x = 0;
            
        }
        if (this.Input[cc.macro.KEY.w] || this.Input[cc.macro.KEY.up]) {
            this.sp.y = -1;
        } else {
            this.sp.y = 0;
        }

        if (this.sp.x != 0) {
            this.lv.x = this.sp.x * this.speed;
        } else {
            this.lv.x = 0
        }

        if (this.sp.y != 0) {
            if (this.isJumping) return;
            cc.tween(this.node).then(this.runJumpAction()).start();
        } else {
            
        }
    }

    // 跳跃方法
    runJumpAction():cc.Tween {
        this.isJumping = true;
        // 跳跃上升
        let jumpUp = cc.tween().by(this.jumpDuration, {y: this.jumpHeight}, {easing: 'sineOut'})

        // 不断重复
        return jumpUp;
    }

    onBeginContact(contact:any, selfCollider, otherCollider) {
        this.isJumping = false;
    }
    update (dt) {
        this.lv = this.node.getComponent(cc.RigidBody).linearVelocity;
        this.moveState();
        this.node.getComponent(cc.RigidBody).linearVelocity = this.lv;
    }
}
